package com.zyd.poi.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zyd.poi.convert.EntityToMapConvert;
import com.zyd.poi.model.WordParam;
import com.zyd.poi.utils.FileUtil;
import com.zyd.poi.utils.PoiUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class PoiController
{
    @Value("${zyd.springboot.param.company}")
    private String company;
    
    private static final ThreadLocal<Long> THREAD_LOCAL = new ThreadLocal<Long>();
    
    @GetMapping("/")
    public ModelAndView index(Model model)
    {
        try
        {
            // properties文件中的中文 默认是以ISO-8859-1的字符编码读取
            // 要想获取真实数据，需要重新编码
            model.addAttribute("company", new String(company.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8.name()));
        }
        catch (UnsupportedEncodingException e)
        {
            log.error(e.getMessage(), e);
        }
        return new ModelAndView("index");
    }
    
    @PostMapping("/build")
    public ResponseEntity<byte[]> build(WordParam wordParam)
        throws IOException
    {
        THREAD_LOCAL.set(System.currentTimeMillis());
        log.info("准备生成绩效考核文件...");
        Map<String, Object> map = EntityToMapConvert.toMap(wordParam);
        for (Entry<String, Object> set : map.entrySet())
        {
            String value = set.getValue().toString().replaceAll("\\r", "").replaceAll("\\n", "\r");
            map.put(set.getKey(), value);
            log.info(set.getKey() + "=[" + value + "]");
        }
        String fileName = PoiUtil.generateFileName(wordParam);
        String expFile = "/opt/tmp/" + fileName;
        File file = null;
        try
        {
            log.info("开始生成绩效考核文件...");
            Resource resource = new ClassPathResource("conf/template.doc");
            PoiUtil.build(resource.getInputStream(), map, expFile);
            log.info("绩效考核文件已生成[{}]...", expFile);
            file = new File(expFile);
            return FileUtil.download(fileName, file);
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
            return null;
        }
        finally
        {
            if (file.exists())
            {
                log.info("清除临时文件{}", expFile);
                file.delete();
            }
        }
    }
}
